package aliyun

import (
	"context"
	"fmt"

	"github.com/gogf/gf/v2/frame/g"
	"github.com/gogf/gf/v2/util/gconv"

	"github.com/beherochuling/beesoft_api/app/helper/net"
)

func NewDingtalk(ctx context.Context, accessToken string) *dingtalk {
	return &dingtalk{
		ctx:         ctx,
		accessToken: accessToken,

		Title:   "我是link类型消息标题",
		Content: "测试 => 我是text类型消息",

		LinkUrl:        "https://open.dingtalk.com/document/robots/custom-robot-access",
		BtnOrientation: 0,
		SingleTitle:    "点击查看详情",
		SingleURL:      "https://open.dingtalk.com/document/robots/custom-robot-access",
	}
}

type dingtalk struct {
	ctx         context.Context
	accessToken string

	Title   string `json:"title"`
	Content string `json:"content"`

	AtMobiles []string `json:"atMobiles"`
	AtUserIds []string `json:"atUserIds"`
	AtAll     bool     `json:"isAtAll"`

	ImageUrl       string `json:"picUrl"`
	LinkUrl        string `json:"messageUrl"`
	BtnOrientation int    `json:"btnOrientation"` // 0：按钮竖直排列，1：按钮横向排列
	SingleTitle    string `json:"singleTitle"`
	SingleURL      string `json:"singleURL"`
}

func (r *dingtalk) url() string {
	return fmt.Sprintf(aliyunDingtalkUrl, r.accessToken)
}
func (r *dingtalk) send(message interface{}) {
	body := net.NewHttp(r.ctx).
		SetContentTypeJson().
		Post(r.url(), message)

	var res *dingtalkResponse
	err := gconv.Scan(body, &res)
	if err != nil {
		panic(err)
	}

	if res.ErrorCode != 0 {
		panic(fmt.Sprintf("dingtalk failed to send message, errcode: %d, errmsg: %s", res.ErrorCode, res.ErrorMessage))
	}
}

func (r *dingtalk) Text() {
	r.send(g.Map{
		"msgtype": "text",
		"text": g.Map{
			"content": r.Content,
		},
		"at": g.Map{
			"atMobiles": r.AtMobiles,
			"atUserIds": r.AtUserIds,
			"isAtAll":   r.AtAll,
		},
	})
}
func (r *dingtalk) Link() {
	r.send(g.Map{
		"msgtype": "link",
		"link":    r,
	})
}
func (r *dingtalk) Markdown() {
	r.send(g.Map{
		"msgtype": "markdown",
		"markdown": g.Map{
			"title": r.Title,
			"text":  r.Content,
		},
		"at": g.Map{
			"atMobiles": r.AtMobiles,
			"atUserIds": r.AtUserIds,
			"isAtAll":   r.AtAll,
		},
	})
}
func (r *dingtalk) ActionCard() {
	r.send(g.Map{
		"msgtype":    "actionCard",
		"actionCard": r,
	})
}
